<template>
    <view class="exam-audio u-flex" @click="onPlay">
        <view v-show="paused">
            <u-image
                src="@/pageFound/static/images/audio_play_icon.png"
                width="104"
                height="104"
            ></u-image>
        </view>
        <view v-show="!paused">
            <u-image
                src="@/pageFound/static/images/audio_pause_icon.png"
                width="104"
                height="104"
            ></u-image>
        </view>
        <view class="title">{{ title }}{{ topicIndex }}</view>
    </view>
</template>

<script>
import { mapState } from "vuex";
export default {
    name: "exam-audio",
    props: {
        src: {
            type: String,
            default: "",
        },
        title: {
            type: String,
            default: "",
        },
        index: {
            type: String,
            default: "",
        },
        topicIndex: {
            type: [String, Number],
            default: 0,
        },
    },
    data() {
        return {
            audioContext: null,
            paused: true, // 是否处于暂停状态
        };
    },
    computed: {
        ...mapState({
            currentPlayerKey: (state) => state.examination.currentPlayerKey,
        }),
    },
    watch: {
        topicIndex() {
            if (this.audioContext) {
                this.audioContext.pause();
                this.paused = true;
            }
        },
        currentPlayerKey(newValue, old) {
            if (newValue != this.index && this.audioContext) {
                this.audioContext.pause();
                this.paused = true;
            }
        },
    },
    mounted() {
        this.audioContext = uni.createInnerAudioContext();
        this.audioContext.src = this.src;
    },
    methods: {
        // 开始/继续播放时
        onPlay() {
            if (this.paused) {
                this.paused = false;
                this.audioContext.play();
            } else {
                this.paused = true;
                this.audioContext.pause();
            }
            this.$store.commit("examination/player", this.index);
        },
    },
    destroyed() {
        this.paused = true;
        this.audioContext.pause();
    },
};
</script>

<style lang="scss" scoped>
.exam-audio {
    .title {
        font-size: 28rpx;
        color: #303133;
        margin-left: 24rpx;
    }
}
</style>
